# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="janos"
__date__ ="$Apr 5, 2011 2:07:44 PM$"

"""
    entrez gene/locuslink:2339
    entrez gene/locuslink:VPS23(gene name synonym)
"""

import sys
from string import join

def main(file_name,identifier_field_name):
    f = open(file_name,'r')
    header_line = f.next()
    header = split_line(header_line)
    f.close()
    (header_pos_dict, pos_header_dict) = header_to_position_hashes(header)

    fw = open(file_name + ".parsed.txt","w")
    fw.write("field_name\tidentifier\tsequence_id\tdb_identifier_type\tdb_identifier\tqualifier\toriginal_value\n")
    for column in header:
        print("Parsing column %s" % column)
        f = open(file_name,'r')
        f.next()
        for line in f:
            mitab_values = split_line(line)
            fw.write(extract_mitab_values(mitab_values[header_pos_dict[column]], column, mitab_values[header_pos_dict[identifier_field_name]]))
        f.close()
    fw.close()

def split_line(line,delimiter="\t"):
    return line.rstrip().split(delimiter)

def header_to_position_hashes(header):
    "Get the position related to the header"
    i = 0
    header_dict={}
    position_dict={}
    for col in header:
        header_dict[col] = i
        position_dict[i] = col
        i += 1
    return (header_dict, position_dict)

def extract_mitab_values(mitab_values, field_name, identifier):
    "entrez gene/locuslink:VPS23(gene name synonym) -> entrez gene/locuslink    VPS23   (gene name synonym)"
    i = 1
    mitab_value_list = mitab_values.split("|")
    mitab_values_string = ""
    for mitab_value in mitab_value_list:
        extracted_mitab_values=extract_mitab_value(mitab_value)
        if extracted_mitab_values:
            if extracted_mitab_values[0] is not None:
                db_identifier_type = extracted_mitab_values[0]
            else:
                db_identifier_type = ""

            if extracted_mitab_values[1] is not None:
                db_identifier = extracted_mitab_values[1]
            else:
                db_identifier = ""

            if extracted_mitab_values[2] is not None:
                qualifier = extracted_mitab_values[2]
            else:
                qualifier = ""

            mitab_values_string += write_out_mitab_value(field_name,identifier,mitab_value,i,db_identifier_type, db_identifier, qualifier)
        else:
            mitab_values_string += write_out_mitab_value(field_name,identifier,mitab_value,i)
        i += 1
    return mitab_values_string

def extract_mitab_value(mitab_value):
    ""
    if ":" in mitab_value:
        if len(mitab_value.split(":")) > 1:
            db_identifier =  mitab_value.split(":")[0]
            identifier = join(mitab_value.split(":")[1:],":")
            if identifier[0] == '"':
                if '"' in identifier[1:]:
                    
                    position_end = identifier[1:].index('"')
                    identifier_cleansed = identifier[1:position_end+1]
                    if position_end < len(identifier):
                        qualifier = identifier[position_end+3:-1]
                    else:
                        qualifier = None
                    return (db_identifier, identifier_cleansed, qualifier)
            else:
                if "(" in identifier and ")" in identifier:
                    identifier_cleansed = identifier.split("(")[0]
                    qualifier = join(identifier.split("(")[1:],"(")[:-1]
                else:
                    qualifier = None
                    identifier_cleansed = identifier
                return (db_identifier, identifier_cleansed, qualifier)
    else:
        return None

def write_out_mitab_value(field_name,identifier,original_value,sequence_id,db_identifier_type="",db_identifier="",qualifier=""):
    ""
    out_string = ""
    for item in (field_name, identifier, str(sequence_id), db_identifier_type, db_identifier, qualifier, original_value):
        if len(item) > 1:
            if item[0] == '"' and item[-1] == '"':
                value = item[1:-1]
            else:
                value = item
        else:
            value = item
        out_string += value + "\t"
    return out_string[:-1] + "\n"

    return "%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (field_name, identifier, sequence_id, db_identifier_type, db_identifier, qualifier, original_value)

if __name__ == "__main__":
#    print(extract_mitab_value('entrez gene/locuslink:"l(1)arm"(gene name synonym)'))
#    print(extract_mitab_value('entrez gene/locuslink:"l(1)arm"'))
#    print(extract_mitab_value('psi-mi:"MI:0401"(biochemical)'))
#    exit()
    main("C:\\users\\janos\\workspace\\biogrid-to-rdf\\files\\BIOGRID-ALL-3.1.75.mitab.txt","Interaction Identifiers")
    if len(sys.argv) == 3:
        main(sys.argv[1], sys.argv[2])
    else:
        print("Usage:\n\tpython biogrid2rdf.py file_name.txt identifier_field_name")
